package com.cse.htmlparser.refactor.yixun;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.Span;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.visitors.NodeVisitor;
import com.cse.core.Product;
import com.cse.htmlparser.AbstractParser;


public class YiXun extends AbstractParser {
	


	
	public YiXun(String html,String file){
		super(html, file);
	}

	/**
	 * 处理catalog下 所有品牌的链接并保存到一个map当中去
	 * @param path
	 */
	//解析文档的方法
	@Override
	protected void extract(){
		//初始化 parser
		initialize(htmlpath);
		
		NodeFilter attfilter = new HasAttributeFilter("class","filter_lk");
		NodeFilter hastitle = new HasAttributeFilter("title");
		NodeFilter andfilter = new AndFilter(hastitle,attfilter);
		try{
		NodeList list = parser.extractAllNodesThatMatch(andfilter);
		NodeIterator iterator = list.elements();
		while(iterator.hasMoreNodes()){
			Node node = iterator.nextNode();
			if(node instanceof LinkTag){
				LinkTag tag = (LinkTag)node;
				String link = tag.getLink();
				String name = tag.getLinkText().replace('×', ' ').trim();
				logger.info("名字:"+name+"  链接"+link);
				map.put(name, link);
			}
		}
		WriteFile();
		}catch(Exception e){
			System.err.print(e);
		}
	}
	
	
	/**
	 * 处理每一个品牌下面的所有类型
	 * 
	 * @param brand 品牌
	 * @param url 
	 */
	@Override
	protected void extractbrand(String brand,String url){
		initialize(url);
		NodeFilter attr = new HasAttributeFilter("class","mod_goods");
		try{
			NodeList list = parser.extractAllNodesThatMatch(attr);
			NodeIterator iterator = list.elements();
			while(iterator.hasMoreNodes()){
				Node node = iterator.nextNode();
				NodeList tag = node.getChildren();
		
				NodeFilter img= new HasAttributeFilter("class","mod_goods_img");
				
				NodeFilter info = new HasAttributeFilter("class","mod_goods_info");
				NodeFilter or = new OrFilter(img,info);
				NodeList childlist = tag.extractAllNodesThatMatch(or);
				Node imgnode = childlist.elementAt(0);
				Node infonode = childlist.elementAt(1);
				final Product product = new Product();
				
				product.setCategory("phone");
				product.setBrand(brand);
				infonode.accept(new NodeVisitor(){

					@Override
					public void visitTag(Tag tag) {
						// TODO Auto-generated method stub
						super.visitTag(tag);
						
						if(tag.getClass() == LinkTag.class)
						{
							if(tag.getAttribute("title") != null && tag.getAttribute("title").length() > 4 ){
								String info = tag.getAttribute("title");
								product.setContent(info);
								logger.info(info);
							
							}
						}
						if(tag.getClass() == Span.class){
							String cattr = tag.getAttribute("class") ;
							cattr = cattr == null ? "" : cattr;
							if(cattr.equals("mod_price") ){
								NodeList list = tag.getChildren();
								Node node = list.extractAllNodesThatMatch(new TagNameFilter("span")).elementAt(0);
								String price = node.toPlainTextString();
								product.setPrice(price);
								logger.info(price);
						
							}
							
						}
					
					}
				});
				imgnode.accept(new NodeVisitor(){

					@Override
					public void visitTag(Tag tag) {
						// TODO Auto-generated method stub
						super.visitTag(tag);
						if(tag.getClass() == LinkTag.class){
							String href = tag.getAttribute("href");
							product.setOriginalUrl(href);
							logger.info(href);
						}
						if(tag.getClass() == ImageTag.class){
							String img = tag.getAttribute("init_src");
							product.setImageURI(img);
							logger.info(img);
						}
					}
					
				});
				product.setUpdatedtime(System.nanoTime()+"");
				indexer.addProduct(product);
			}
			//indexer.optimizeIndex();
		}catch(Exception e){
			System.err.print(e);
		}
		
	}
	
	/**
	 * 处理该map下所有的品牌
	 * 
	 */
	@Override
	protected void extractall(){
		try{
			Map<String,String> mapbrand = getMap();
			Iterator<Entry<String,String>>  iterator = mapbrand.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String,String> entry = (Entry<String,String>) iterator.next(); 
				String brand = entry.getKey();
				String url = entry.getValue();
				extractbrand(brand,url);
			}
			indexer.optimizeIndex();
			indexer.close();
		}catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		}
	}
	
	
	/**
	 * 对外执行的函数，执行extract以及extratall（）方法
	 */
	public void startExtract(){
		extract();
		extractall();
	}		
	
	public static void main(String[] args){
	
	
	}
}
	

